<?php

namespace app\index\controller;

use app\common\controller\IndexBase;
use app\common\controller\PcUserBase;
use app\common\controller\UserBase;
use app\common\helper\NetPay;
use app\common\helper\SendSmsHelper;
use app\common\logic\OrderLogic;
use app\common\model\Address;
use app\common\model\Archives;
use app\common\model\Cart;
use app\common\model\Goods as goodsModel;
use app\common\model\lawyer\Deal;
use app\common\model\Need;
use app\common\model\Order;
use app\common\validate\lawyer\DealValidate;
use app\common\validate\UserValidate;
use GuzzleHttp\Exception\ClientException;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Queue;
use think\facade\View;
use think\helper\Str;

class User extends PcUserBase
{
    protected $user;
    protected $uid;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $view = [
            "hover" => '',
            "user" => $this->user
        ];
        View::assign($view);
    }
    
    // 基本信息
    public function base()
    {
        return View::fetch();
    }

    public function treat()
    {
        return View::fetch();
    }
    

    // 更新用户
    public function updateUser()
    {
        $data = (new \app\index\validate\UserValidate())->doCheck('update');
        $this->user->save([
            "avatar" => $data['avatar'],
            "nick" => $data['nick'],
            "sex" => $data['sex'],
            "age" => $data['age'],
            "company" => $data['company'],
        ]);
        $this->success();
    }
    
    // 合同管理
    public function contract()
    {
        $where = [];
        if (isset($this->data['status'])) {
            $where[] = ['status',"=",$this->data['status']];
        }
        $list = \app\common\model\lawyer\Deal::where("user_id",$this->uid)
            ->where($where)
            ->paginate(['list_rows'=>$this->limit,"page"=>$this->page]);
        View::assign("list",$list);
        return View::fetch();
    }
    // 添加合同
    public function addDeal()
    {
        $data = (new DealValidate())->doCheck('add');
        $data['user_id'] = $this->uid;
        $data["status"] = -1;
        if (!empty($data['id'])) {
            \app\common\model\lawyer\Deal::update($data);
        } else {
            \app\common\model\lawyer\Deal::create($data);
        }
        $this->success();
    }
    
    
    public function car()
    {
        return View::fetch();
    }
    public function my()
    {
        $flag = md5(time() . 'htttttc');
        session('flag',$flag,300);
        View::assign('flag',$flag);
        return View::fetch();
    }
    public function userUpdate() {
        $user = \app\common\model\User::find($this->uid);
        $user->save($this->data);
        $this->success();
    }
    public function sendSms()
    {
        $data = safeInput();
        $rule = [
            "flag|令牌" => "require"
        ];
        try {
            $this->validate($data,$rule);
            if ($data['flag'] !== session("flag")) {
                return $this->error("发送失败，请刷新重试");
            }
        } catch (ValidateException $exception) {
            return  $this->error($exception->getMessage());
        }
        $ming = new SendSmsHelper();
        $result = $ming->sendSms($this->user->tel,'forget');
        if ($result['code'] == 1) $this->success();
        return $this->error($result['msg']);
    }

    public function changePassword()
    {
        $rule = [
            "password|密码" => 'require',
            "code|验证码" => 'require'
        ];
        $user = \app\common\model\User::find($this->uid);
        try {
            $this->validate($this->data,$rule);
            $sms = new SendSmsHelper();
            if (!$sms->checkYzm(['tel'=>$user->tel,'code'=>$this->data['code'],'type'=>'forget'])) {
                throwError('验证码错误');
            }
            $user->save([
                "password" => password_hash($this->data['password'],PASSWORD_DEFAULT)
            ]);
            $this->success();
        } catch (ValidateException | Exception $exception) {
            throwError($exception->getMessage());
        }
    }

    public function complete()
    {
        return View::fetch();
    }

    public function order()
    {
        $status = input('status','');
        $list = OrderLogic::getOrderList($this->data);
        View::assign('list',$list);
        View::assign('status',$status);
        return View::fetch();
    }

    public function orderDetail()
    {
        $order = Order::where("id",$this->data['id'])->with(['item','address'])->find();
        View::assign('order',$order);
        return View::fetch();
    }

    public function address()
    {
        $list = Address::where("user_id",$this->uid)->select();
        View::assign('address',$list);
        return View::fetch();
    }

    public function addAddress()
    {
        try {
            $this->validate($this->data,\app\validate\Address::class);
            if ($this->data['is_default'] == 1) {
                Address::where("user_id",$this->uid)->save(["is_default"=>0]);
            }
            if (!empty($this->data['id'])) {
                $address = Address::update($this->data);
            } else {
                $address = Address::create($this->data);
            }
            $this->success($address);
        } catch (ValidateException |Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    public function selfPay()
    {
        Db::startTrans();
        try {
            $data = input();
            $archivesUser = ArchivesUser::where("id",$data['id'])->find();
            if ($archivesUser->status != 1) {
                $this->error('订单已经完成，无需支付');
            }

            $archives = Archives::find($archivesUser['archives_id']);
            if ($archives->getData('end_time') < time()) {
                $this->error('活动已过期');
            }
            $needMoney = $archivesUser->total - $archivesUser->money;

            $pay = new NetPay();
            $wx = $pay->pay_init();
            $out_trade_no = date("YmdHis") . Str::random(6,1);
            $v3 = [
                'mchid'        => $this->Config['wx_mchid'],
                'out_trade_no' => $out_trade_no,
                'appid'        => $this->Config['wx_appid'],
                'description'  => "报名费用",
                'notify_url'   => $this->app->request->domain() . url('Pay/notify'),
                'amount'       => [
                    'total'    => $needMoney * 100,
                    'currency' => 'CNY'
                ],
                'payer'        => [
                    'openid' => session('user.wx_openid')
                ]
            ];

            $support = SupportUser::create([
                "archives_id" => $archivesUser['archives_id'],
                "archives_user_id" => $archivesUser['id'],
                "money" => $needMoney,
                "user_id" => session('user.id'),
                "show" => empty($data['is']) ? 0 : 1,
                "content" => $archivesUser['content']
            ]);
            PayLog::create([
                "out_trade_no" => $out_trade_no,
                "user_id" => session("user.id"),
                "archives_user_id" => $archivesUser->id,
                "money" => $needMoney,
                "support_user_id" => $support->id
            ]);
            $result = $wx->v3->pay->transactions->jsapi
                ->post(['json'=>$v3]);
            $res = json_decode($result->getBody(),true);
            $param = $pay->getPayStr($res['prepay_id']);
            Db::commit();
            $this->success($param);
        } catch (ClientException | Exception $exception) {
            Db::rollback();
            $res = mb_convert_encoding($exception->getMessage(), 'UTF-8', 'UTF-8');
            $this->error($res);
        }

    }


    public function supportPay()
    {
        $data = input();
        Db::startTrans();
        try {
            $rule = [
                "archives_id|活动" => 'require',
                "archives_user_id|个人信息" => 'require',
                "content|宣言" => "require"
            ];
            $this->validate($data,$rule);
            $archives = Archives::find($data['archives_id']);
            if ($archives->getData('end_time') < time()) {
                $this->error('活动已过期');
            }
            $archivesUser = ArchivesUser::find($data['archives_user_id']);
            if ($archivesUser->status != 1) {
                $this->error('任务已完成,无需支持');
            }
            $support = SupportUser::create([
                "archives_id" => $data['archives_id'],
                "archives_user_id" => $data['archives_user_id'],
                "money" => $data['money'],
                "user_id" => $archivesUser->user_id,
                "show" => empty($data['is']) ? 0 : 1,
                "content" => $data['content']
            ]);
            $pay = new NetPay();
            $wx = $pay->pay_init();
            $out_trade_no = date("YmdHis") . Str::random(6,1);
            $v3 = [
                'mchid'        => $this->Config['wx_mchid'],
                'out_trade_no' => $out_trade_no,
                'appid'        => $this->Config['wx_appid'],
                'description'  => "支持费用",
                'notify_url'   => $this->app->request->domain() . url('Pay/notify'),
                'amount'       => [
                    'total'    => $data['money'] * 100,
                    'currency' => 'CNY'
                ],
                'payer'        => [
                    'openid' => session('user.wx_openid')
                ]
            ];
            PayLog::create([
                "out_trade_no" => $out_trade_no,
                "user_id" => session("user.id"),
                "archives_user_id" => $archivesUser->id,
                "money" => $data['money'],
                "support_user_id" => $support->id
            ]);
            Db::commit();
            $result = $wx->v3->pay->transactions->jsapi
                ->post(['json'=>$v3]);
            $res = json_decode($result->getBody(),true);
            $param = $pay->getPayStr($res['prepay_id']);
            $this->success($param);

        } catch (ValidateException | Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }
}